package com.gopay.checkorder.service.impl.expay;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.IcbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.icbc.expay.query.req.IcbcQueryExpayCmsReq;
import com.gopay.common.domain.bank.icbc.expay.query.res.IcbcQueryExpayCmsRes;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/** 
 * 工行快捷对账接口实现
 * @ClassName: CheckOrderIcbcExPayImpl 
 * @author w_jiqing 
 * @date 2017年6月29日 下午5:20:50  
 */ 
public class CheckOrderIcbcExPayImpl implements BankOrderService{
    
    private final static Logger logger = LoggerFactory.getLogger(CheckOrderIcbcExPayImpl.class);
    
    @Resource(name = "bankExPayClient")
    private ExPayInteractRemoteService bankExPayClient;

    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());

        IcbcQueryExpayCmsReq base = new IcbcQueryExpayCmsReq();
        base.setOrderId(bankOrder.getOrderId());
        base.setBankOrderId(bankOrder.getOutOrderId());
        base.setBank(BankConstants.BANK_LOGO_ICBC);
        base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
        base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
        
        Result result = new Result();
        try{
            result = bankExPayClient.queryOrder(base);
            if (result == null || !result.isSuccess()) {
                logger.error("bankClient fail.");
                if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
                    BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                }
                logger.error(ToStringBuilder.reflectionToString(result,ToStringStyle.DEFAULT_STYLE));
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("系统返回对账结果为空");
                return checkOrderResult;
            }

            IcbcQueryExpayCmsRes res =  (IcbcQueryExpayCmsRes) result.getDefaultModel();
            if (res == null) {
                // 查询订单为空
                logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
                checkOrderResult.setErrMsg("银行返回对账结果为空");
            }
            String retCode = res.getEb().getPub().getRetCode();
            String retMsg = res.getEb().getPub().getRetMsg();
            if(retCode != null && !IcbcConstants.ICBC_EXPAY_RETCODE_SUCCESS.equals(retCode)){
             // 查询订单错误
                logger.error("orderId: " + bankOrder.getOrderId()+ " retCode:" + retCode + " retMsg:" + retMsg);
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
                checkOrderResult.setErrMsg("银行返回对账结果为空");
                return checkOrderResult;
            }
            String orderStatus = res.getEb().getOut().getResult();
            if(orderStatus.equals(IcbcConstants.ICBC_EXPAY_QUERY_SUCCESS)){
                //支付成功
                checkOrderResult.setSuccess(true);
                InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(base.getOrderId()); 
                String amount = TransUtil.amountConvert2Yuan(res.getEb().getOut().getOrderAmt());
                accInfo.setAmount(new BigDecimal(amount));
                accInfo.setRetCode("00");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
                logger.error("工商银行快捷订单:" + base.getOrderId()+ ",交易成功，查到的订单状态:" + orderStatus);
            }else if(orderStatus.equals(IcbcConstants.ICBC_EXPAY_QUERY_FAIL)){
                //交易失败
                InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(base.getOrderId());
                String amount = TransUtil.amountConvert2Yuan(res.getEb().getOut().getOrderAmt());
                accInfo.setAmount(new BigDecimal(amount));
                accInfo.setRetCode("01");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
                checkOrderResult.setBankFailure(true);
                logger.error("工商银行快捷订单:" + base.getOrderId()+ ",交易失败，查到的订单状态:" + orderStatus);
                checkOrderResult.setErrMsg("银行返回交易失败");
            }else if(orderStatus.equals(IcbcConstants.ICBC_EXPAY_QUERY_SUSPICIOUS)){
                //交易可疑
                logger.error("工商银行快捷订单:" + base.getOrderId()+ ",交易可疑，查到的订单状态:" + orderStatus);
                checkOrderResult.setErrMsg("银行返回处理中");
            }else if(orderStatus.equals(IcbcConstants.ICBC_EXPAY_QUERY_OVER_FAILS)){
                //超过当日错误次数
                logger.error("工商银行快捷订单:" + base.getOrderId()+ ",超过当日错误次数，查到的订单状态:" + orderStatus);
                checkOrderResult.setErrMsg("银行返回处理中");
            }else if(orderStatus.equals(IcbcConstants.ICBC_EXPAY_QUERY_OVER_HISTORY)){
                //超过历史错误次数
                logger.error("工商银行快捷订单:" + base.getOrderId()+ ",超过历史错误次数，查到的订单状态:" + orderStatus);
                checkOrderResult.setErrMsg("银行返回处理中");
            }else if(orderStatus.equals(IcbcConstants.ICBC_EXPAY_QUERY_SMS_FAIL)){
                //支付密码校验失败
                logger.error("工商银行快捷订单:" + base.getOrderId()+ ",支付密码校验失败，查到的订单状态:" + orderStatus);
                checkOrderResult.setErrMsg("银行返回处理中");
            }else{
                logger.error("工商银行快捷订单:" + base.getOrderId()+ "，查到的订单状态:" + orderStatus);
                checkOrderResult.setErrMsg("银行返回处理中");
            }
            
            return checkOrderResult;
        }catch (Exception e) {
            logger.error("bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("对账调用bis失败");
            return checkOrderResult;
        }
        
    }

    @Override
    public BankOrder getDbOrder() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BaseMessage dayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result getDayendMsg(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<CheckOrderResult> checkDayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
        // TODO Auto-generated method stub
        return null;
    }

}
